﻿using System;
using System.Windows.Forms;
using ApplicationLibrary;
using ApplicationLibrary.DBManager;
using ApplicationLibrary.ExtendedControls;
using ApplicationLibrary.SqlConnector;
using Plumber.Accounting.Forms;
using Plumber.Accounting.ModuleData;
using Plumber.Accounting.Reports.DataSet;
using Plumber.Masters.ModuleData;

namespace Plumber.Accounting.Reports
{
    public partial class MonthlySummary : ApplicationLibrary.DBManager.ReportForm
    {
        private string Title = string.Empty;
        private EnumsManager<PeriodType> eMonthName = null;
        private DSJournalEntries dsMonthlySummary = null;
        private DRMasterType drMasterType;
        private DRJournalEntry drJournalEntry = null;
        private DRMasters drMasters = null;
        private double prevFrom = 0, prevTo = 0;
        private int prevMonth = 0, prevYear = 0;

        public MonthlySummary()
            : base(Properties.Resources.FN_MonthlySummary)
        {
            InitializeComponent();
        }

        protected override void OnBatchExecute(string reportName)
        {
            Title = string.Format("{0}_{1}_{2}", Properties.Resources.FN_MonthlySummary, cbbMonth.Text, cbbYear.Text);
            if (!LoadData())
            {
                MessageBox.Show(Properties.Resources.Msg_NoDataPeriod, Properties.Resources.Warning, MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            SetParameterValue("ShowPrev", ckbShowPrev.Checked);

                SetParameterValue("prevFrom", prevFrom);
                SetParameterValue("prevTo", prevTo);
                SetParameterValue("previousPeriod", ckbShowPrev.Checked
                                ? string.Format(Properties.Resources.Msg_PreviousPeriod,eMonthName.GetText(prevMonth - 1), prevYear)
                                : "");

            SetParameterValue("Title", string.Format(Properties.Resources.Msg_MonthlySummary,
                cbbMonth.Text, cbbYear.Text));
            ShowReport(new RPTMonthlySummary(), dsMonthlySummary);
            int a = GetPages();
        }

        protected override void OnDisableControlsForRun()
        {
        }

        protected override void OnAttachData()
        {
            eMonthName = new EnumsManager<PeriodType>(cbbMonth);
            cbbMonth.SelectedValue = GlobalInfo.CurrentDate.Month;
            cbbYear.Text = GlobalInfo.CurrentDate.Year.ToString();

            dsMonthlySummary = new DataSet.DSJournalEntries();
            drMasterType     = new DRMasterType(DRMasterType.Module.All);
            drJournalEntry   = new DRJournalEntry(false);
            drMasters        = new DRMasters(false);

            for (int t = 2011; t <= GlobalInfo.CurrentDate.Year; t++)
                cbbYear.Items.Add(t);

            cbbYear.Text  = GlobalInfo.CurrentDate.Year.ToString();
            cbbMonth.Text = eMonthName.GetText(GlobalInfo.CurrentDate.Month - 1);

            AddClickableColumn(PL_JournalEntryDetail.JournalNo);
        }

        protected override void OnDoubleClickColumn(string column, string value, CrystalDecisions.Windows.Forms.ObjectInfo[] objectInfo)
        {
            if (drJournalEntry.Find(value))
            {
                if (drJournalEntry.GetValue<TaxRegisterType>(PL_JournalEntry.TaxRegister) == TaxRegisterType.E_NORegister)
                {
                    JournalEntries frm = (JournalEntries)GlobalInfo.OpenForm("Plumber.Plumber.Accounting.Forms.JournalEntries", false);
                    frm.FindRecord(new RadarJournalEntryParam(value));
                }
                else
                {
                    JournalEntriesSalePurchase frm = (JournalEntriesSalePurchase)GlobalInfo.OpenForm("Plumber.Plumber.Accounting.Forms.JournalEntriesSalePurchase", false);
                    frm.FindRecord(new RadarJournalEntryParam(value));
                }
            }
        }

        protected override void OnBindData()
        {
        }

        private bool LoadData()
        {
            dsMonthlySummary.Clear();
            prevFrom = 0;
            prevTo = 0;

            QueryBuilder qb = new QueryBuilder(true);
            qb.SetQualified = true;

            // Previous period
            if (ckbShowPrev.Checked)
            {
                prevMonth = (int)eMonthName.GetValue() - 1;
                prevYear = int.Parse(cbbYear.Text);
                if (prevMonth == 0)
                {
                    prevMonth = 12;
                    prevYear--;
                }
                DateTime prevPeriodStart = new DateTime(prevYear, 1, 1);
                DateTime prevPeriodTo = new DateTime(prevYear, prevMonth, DateTime.DaysInMonth(prevYear, prevMonth));

                qb.AddFunctionAs("SUM({0})", PL_JournalEntryDetail.From);
                qb.AddFunctionAs("SUM({0})", PL_JournalEntryDetail.To);
                qb.AddFrom(PL_JournalEntryDetail.Name);
                qb.AddJoin(QueryBuilder.JoinType.INNER, PL_JournalEntry.JournalNo, PL_JournalEntryDetail.JournalNo);
                qb.AddBetween<DateTime>(PL_JournalEntry.PostingDate, prevPeriodStart, prevPeriodTo);

                using (SqlABCommand scc = new SqlABCommand(base.providerType, GlobalInfo.SqlConnection))
                {
                    scc.CommandText = qb.Query;
                    SqlABDataReader dr = scc.ExecuteReader();
                    if (dr.Read())
                    {
                        prevFrom = dr.GetValue<double>(PL_JournalEntryDetail.From);
                        prevTo = dr.GetValue<double>(PL_JournalEntryDetail.To);
                    }
                    dr.Close();
                }
            }

            qb.Clear();
            qb.AddSelect(PL_JournalEntry.PostingDate);
            qb.AddSelectAS(PL_JournalEntry.Description, "HeaderDescription");
            qb.AddSelect(PL_JournalEntry.TaxRegister);

            qb.AddSelectAll(PL_JournalEntryDetail.Name);
            qb.AddFrom(PL_JournalEntryDetail.Name);
            qb.AddJoin(QueryBuilder.JoinType.INNER, PL_JournalEntry.JournalNo, PL_JournalEntryDetail.JournalNo);
            SqlABParameter pFrom = new SqlABParameter("@p1", PL_JournalEntry.PostingDate);
            SqlABParameter pTo = new SqlABParameter("@p2", PL_JournalEntry.PostingDate);
            qb.AddBetween(PL_JournalEntry.PostingDate, pFrom, pTo);
            qb.AddOrder(PL_JournalEntry.PostingDate);
            qb.AddOrder(PL_JournalEntry.JournalNo);

            DateTime startPeriod, endPeriod;

            if (cbbMonth.SelectedIndex > 11)
            {
                startPeriod = new DateTime(int.Parse(cbbYear.Text), (((int)eMonthName.GetValue())-13)*3+1, 1);
                endPeriod = new DateTime(int.Parse(cbbYear.Text), (((int)eMonthName.GetValue()) - 12) * 3, DateTime.DaysInMonth(int.Parse(cbbYear.Text), (((int)eMonthName.GetValue()) - 12) * 3));
            }
            else
            {
                startPeriod = new DateTime(int.Parse(cbbYear.Text), (int)eMonthName.GetValue(), 1);
                endPeriod = new DateTime(int.Parse(cbbYear.Text), (int)eMonthName.GetValue(), DateTime.DaysInMonth(int.Parse(cbbYear.Text), (int)eMonthName.GetValue()));
            }
            pFrom.Value = startPeriod;
            pTo.Value = endPeriod;

            string oldJN = string.Empty;

            using (SqlABCommand scc = new SqlABCommand(base.providerType, GlobalInfo.SqlConnection))
            {
                scc.CommandText = qb.Query;
                scc.Parameters.Add(pFrom);
                scc.Parameters.Add(pTo);
                SqlABDataReader dr = scc.ExecuteReader();
                while (dr.Read())
                    AddRow(dr);
                dr.Close();
            }

            return dsMonthlySummary.JournalEntryDetail.Rows.Count > 0;
        }

        private void AddRow(SqlABDataReader dr)
        {
            DataSet.DSJournalEntries.JournalEntryDetailRow jer = dsMonthlySummary.JournalEntryDetail.NewJournalEntryDetailRow();
            jer["Aggregator"] = string.Empty;
            jer[PL_JournalEntryDetail.JournalNo.Name] = dr.GetValue<string>(PL_JournalEntryDetail.JournalNo);
            jer[PL_JournalEntryDetail.JournalNo.Name] = dr.GetValue<string>(PL_JournalEntryDetail.JournalNo);
            jer[PL_JournalEntryDetail.Line.Name] = dr.GetValue<int>(PL_JournalEntryDetail.Line);
            jer[PL_JournalEntry.PostingDate.Name] = dr.GetValue<DateTime>(PL_JournalEntry.PostingDate);

            drMasterType.Find(dr.GetValue<string>(PL_JournalEntryDetail.Type));
            jer[PL_JournalEntryDetail.Type.Name] = drMasterType.GetValue<string>(PL_MasterType.Description);

            if (dr.GetValue<int>(PL_JournalEntry.TaxRegister) == TaxRegisterType.E_NORegister.Int())
            {
                if (drMasters.Find(dr.GetValue<string>(PL_JournalEntryDetail.Type), dr.GetValue<string>(PL_JournalEntryDetail.Code)))
                    jer[PL_JournalEntryDetail.Code.Name] = drMasters.GetValue<string>(PL_Masters.Description);
                else
                    jer[PL_JournalEntryDetail.Code.Name] = dr.GetValue<string>(PL_JournalEntryDetail.Code);
            }
            else
            {
                jer[PL_JournalEntryDetail.Code.Name] = dr.GetString("HeaderDescription");
            }
            jer[PL_JournalEntryDetail.Description.Name] = dr.GetValue<string>(PL_JournalEntryDetail.Description);
            jer[PL_JournalEntryDetail.From.Name] = dr.GetValue<double>(PL_JournalEntryDetail.From);
            jer[PL_JournalEntryDetail.To.Name] = dr.GetValue<double>(PL_JournalEntryDetail.To);

            dsMonthlySummary.JournalEntryDetail.Rows.Add(jer);
        }

        protected override EmailArgs SendEmail()
        {
            EmailArgs ea = new EmailArgs();
            ea.Subject = Title;
            ea.Attachment = ExportToPdf(Title);
            return ea;
        }
    }
}